#-*- coding:utf-8 -*-

import pandas as pd, time,numpy as np
from datetime import datetime

csvfile = pd.read_csv(r"K:\MOOC\Stock\stock data\stock_analysis_draft1\sh600897.csv",sep=",",parse_dates= ['date'])
print(csvfile.head())

sorted_csv = csvfile.sort_values( by = 'date',ascending=True)
# print('sorted',sorted_csv.head())
record_frame = pd.DataFrame(columns=('code','start_date','start_price','min_bf_max_date','min_bf_max_price','max_date','max_price','min_af_max_date','min_af_max_price','increase_rate','increase_day','decrease_rate','decrease_day'))
start_from = 60
small_gap = 180

for i in range(0,len(sorted_csv)-start_from-small_gap):
    sub_range = sorted_csv.ix[len(sorted_csv)-start_from-i:len(sorted_csv)-start_from-i-small_gap,['date','adjust_price_f']]
    sub_max_price = max(sub_range['adjust_price_f'])
    sub_max_date_id = sub_range.loc[sub_range['adjust_price_f'] == sub_max_price,'date']
    sub_max_date = list(sub_max_date_id)[0]
    sub_range_bf = sub_range.ix[:sub_max_date_id.index[0]]
    sub_min_bf_max_price = min(sub_range_bf['adjust_price_f'])
    sub_min_bf_max_date_id = sub_range_bf.ix[sub_range_bf['adjust_price_f'] == sub_min_bf_max_price,'date']
    sub_min_bf_max_date = list(sub_min_bf_max_date_id)[0]
    sub_range_af = sub_range.ix[sub_max_date_id.index[0]:]
    sub_min_af_max_price = min(sub_range_af['adjust_price_f'])
    sub_min_af_max_date_id = sub_range_af.ix[sub_range_af['adjust_price_f'] == sub_min_af_max_price,'date']
    sub_min_af_max_date = list(sub_min_af_max_date_id)[0]
    sub_start_price = sub_range.ix[len(sorted_csv)-start_from-i,'adjust_price_f']
    sub_start_date = sub_range.ix[len(sorted_csv)-start_from-i,'date']
    code = sorted_csv['code'][0]
    increase_rate = (sub_max_price-sub_min_bf_max_price)/sub_min_bf_max_price
    increase_day = abs(sub_max_date - sub_min_bf_max_date)
    decrease_rate =(sub_min_af_max_price-sub_max_price)/sub_max_price
    decrease_day = abs(sub_min_af_max_date - sub_max_date)
    data = [code,sub_start_date,sub_start_price,sub_min_bf_max_date,sub_min_bf_max_price,sub_max_date,sub_max_price,sub_min_af_max_date,sub_min_af_max_price,increase_rate,increase_day,decrease_rate,decrease_day]
    record_frame.loc[i,:] = data

pivot_record_frame = pd.pivot_table(data=record_frame,values='start_date',columns=['code','min_bf_max_date','min_bf_max_price','max_date','max_price','min_af_max_date','min_af_max_price','increase_rate','increase_day','decrease_rate','decrease_day'],aggfunc = min)
print(pivot_record_frame)
#
# conso_collection = record_frame.groupby(by = ['increase_rate','decrease_rate'])
# print(conso_collection)
#
# print(record_frame)
pivot_record_frame.to_csv(str(code)+str(small_gap)+".csv")
#
